import React, { useLayoutEffect, useState } from 'react';
import style from './index.less';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { CheckOutlined, LockOutlined, UserOutlined } from '@ant-design/icons';
import { Alert, message } from 'antd';
import { login, queryCurrentUser, wechatLog, wechatSelectLogin } from '@/services/user/api';
import { Role, SUCCESS_CODE } from '@/utils/types.d';
import { useModel } from 'umi';
import { getWxLoginConfig } from './service';

const NewLogin: React.FC = () => {
  //   const [type] = useState<string>('account')
  const randomCode = String((Math.random() * 1000000) << 2);
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [selectedUserid, setSelectedUserid] = useState<string>('');
  const [type, setType] = useState<string>('account');
  const { wxLoginSwitch, setWxConfig } = useModel('wxconfig');
  const LoginMessage: React.FC<{
    content: string;
  }> = ({ content }) => (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
  const [userList, setUserList] = useState<
    {
      userid: string;
      userName: string;
      ownerId: string;
      account: string;
    }[]
  >([]);
  const { initialState, setInitialState } = useModel('@@initialState');

  // eslint-disable-next-line @typescript-eslint/no-shadow
  const fetchUserInfo = async () => {
    const userInfo = await queryCurrentUser();
    if (userInfo) {
      setInitialState({
        ...initialState,
        currentUser: userInfo,
      });
    }
    return userInfo;
  };
  const hashChangeEv = (ev: HashChangeEvent) => {
    if (!wxLoginSwitch) return;
    const args = ev.newURL.split('?');
    if (args.length < 2) {
      // message.error({
      //   content: '微信登录失败，请使用账号密码登录',
      //   key: 'login_msg',
      // });
      setType('account');
      return;
    }
    const search = new URLSearchParams(args[1]);
    if (search.get('redirect')) {
      return;
    }
    // 当前umi/history定义中无query属性，所以这里使用search
    // const search = new URLSearchParams(location.search);
    const code = search.get('code');
    const state = search.get('state');
    if (!code) {
      console.log('无法获取code属性，说明是微信登录失败');
      // 无法获取code属性，说明是微信登录失败
      message.error({
        content: '微信登录失败，请使用账号密码登录',
        key: 'login_msg',
      });
      setType('account');
      return;
    }
    if (state !== randomCode) {
      console.log('防止伪造state');
      // 防止伪造state
      message.error({
        content: '微信登录失败，请使用账号密码登录',
        key: 'login_msg',
      });
      setType('account');
      return;
    }
    wechatLog(code).then((res) => {
      if (res?.code === SUCCESS_CODE) {
        // 1. data.flag == bind
        if (res?.data.flag === 'bind') {
          message.error({
            content: '当前微信未绑定用户，请使用账号密码登录',
            key: 'login_msg',
          });
          setType('account');
          return false;
        }
        // 2. data.flag == select
        if (res?.data.flag === 'select') {
          //绑定了多个用户的情况下
          // TODO: 跳转用户选择界面
          setUserList(res?.data.userList || []);
          setType('select');
          return true;
        }
        // 3. data.flag == ok
        if (res?.data.flag === 'ok') {
          fetchUserInfo().then((user) => {
            // window.location.href = '#/';
            window.location.href = user.role == Role.ADMIN ? '#/' : '#/dashboard';
            message.success({
              content: '微信登录成功',
              key: 'login_msg',
            });
            return true;
          });
        }
        return true;
      }
      message.error({
        content: '微信登录失败，请使用账号密码登录',
        key: 'login_msg',
      });
      setType('account');
      return false;
    });
  };
  useLayoutEffect(() => {
    getWxLoginConfig().then((res) => {
      if (!res.success) return;
      const { ifWxLogin: iw, wxAppId, wxRedirectUri } = res.data;
      if (!iw) return;
      setWxConfig(res.data);
      console.log('微信============>', wxAppId, wxRedirectUri);
      //@ts-ignore
      let WxLogin: WxLogin = window.WxLogin;
      if (type !== 'select') {
        window.addEventListener('hashchange', hashChangeEv);
        if (!WxLogin) {
          const wxScript = document.createElement('script');
          wxScript.type = 'text/javascript';
          wxScript.src = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js';
          document.getElementById('root')?.appendChild(wxScript);
          wxScript.onload = () => {
            //@ts-ignore
            WxLogin = window.WxLogin;
            WxLogin({
              id: 'wx_login',
              appid: wxAppId,
              scope: 'snsapi_login,snsapi_userinfo',
              redirect_uri: encodeURIComponent(`${wxRedirectUri}/#/user/login`),
              state: randomCode,
              href: 'data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDIwMHB4O30KLmltcG93ZXJCb3ggLnRpdGxlIHtkaXNwbGF5OiBub25lO30KLmltcG93ZXJCb3ggLmluZm8ge3dpZHRoOiAyMDBweDt9Ci5zdGF0dXNfaWNvbiB7ZGlzcGxheTogbm9uZX0KLmltcG93ZXJCb3ggLnN0YXR1cyB7dGV4dC1hbGlnbjogY2VudGVyO2NvbG9yOiNmZmZ9IA==',
            });
          };
        } else {
          WxLogin({
            id: 'wx_login',
            appid: wxAppId,
            scope: 'snsapi_login,snsapi_userinfo',
            redirect_uri: encodeURIComponent(`${wxRedirectUri}/#/user/login`),
            state: randomCode,
            href: 'data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDIwMHB4O30KLmltcG93ZXJCb3ggLnRpdGxlIHtkaXNwbGF5OiBub25lO30KLmltcG93ZXJCb3ggLmluZm8ge3dpZHRoOiAyMDBweDt9Ci5zdGF0dXNfaWNvbiB7ZGlzcGxheTogbm9uZX0KLmltcG93ZXJCb3ggLnN0YXR1cyB7dGV4dC1hbGlnbjogY2VudGVyO2NvbG9yOiNmZmZ9IA==',
          });
        }
      } else {
        window.removeEventListener('hashchange', hashChangeEv);
      }
      if (type === 'select') {
        window.removeEventListener('hashchange', hashChangeEv);
      }
      return () => {
        window.removeEventListener('hashchange', hashChangeEv);
      };
      // eslint-disable-next-line react-hooks/exhaustive-deps
    });
  }, [type]);

  const { code, message: mmsg } = userLoginState;

  return (
    <div className={style.login}>
      <div className={style.box}>
        {type !== 'select' && wxLoginSwitch && (
          <div className={style.left}>
            <div className={style.title}>扫码登录</div>
            <div id="wx_login" style={{ width: '300px' }} />
          </div>
        )}
        <LoginForm
          className={style.loginForm}
          title="一九智慧停车"
          subTitle={'停车收费管理平台'}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            try {
              let msg: API.LoginResult = {
                code: -1,
                message: '登录失败，请重试！',
              };
              // 登录
              if (type === 'account') {
                msg = await login({ ...values });
              }
              if (type === 'select') {
                if (!selectedUserid) {
                  setUserLoginState({
                    code: -1,
                    message: '请选择要登录的用户',
                  });
                  return;
                }
                msg = await wechatSelectLogin(selectedUserid);
              }
              if (msg?.code === SUCCESS_CODE) {
                const user = await fetchUserInfo();
                // /dashboard
                window.location.href = user.role == Role.ADMIN ? '#/' : '#/dashboard';
                const defaultLoginSuccessMessage = '登录成功！';
                message.success({ content: defaultLoginSuccessMessage, key: 'login_msg' });
                return;
              }
              // 如果失败去设置用户错误信息
              setUserLoginState(msg);
              return;
            } catch (error) {
              const defaultLoginFailureMessage = '登录失败，请重试！';
              message.error({ content: defaultLoginFailureMessage, key: 'login_msg' });
              return;
            }
          }}
        >
          {type !== 'select' && (
            <>
              <ProFormText
                name="account"
                width="lg"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={style.prefixIcon} />,
                }}
                placeholder={'用户名'}
                rules={[
                  {
                    required: true,
                    message: '请输入用户名!',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                width="lg"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={style.prefixIcon} />,
                }}
                placeholder={'密码'}
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                ]}
              />
            </>
          )}
          {typeof code === 'number' && code !== SUCCESS_CODE && (
            <LoginMessage content={mmsg || '账户或密码错误'} />
          )}
          {type === 'select' && (
            <>
              <h3 style={{ color: '#fff' }}>请选择要登录的账号</h3>
              <ul className={style.userSelectWrap}>
                {userList.map((item) => (
                  <li
                    className={style.userSelectItem}
                    key={item.account}
                    onClick={() => {
                      setUserLoginState({});
                      setSelectedUserid(item.userid);
                    }}
                  >
                    <span className={style.itemAccount}>
                      {item.userName}（{item.account}）
                    </span>
                    <span>
                      {selectedUserid === item.userid && (
                        <CheckOutlined style={{ color: '#55ff00' }} />
                      )}
                    </span>
                  </li>
                ))}
              </ul>
            </>
          )}
        </LoginForm>
      </div>
    </div>
  );
};

export default NewLogin;
